package com.starpl.mobile.android.monthunsae.november.handler;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.activity.CommunityCommentActivity;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.StarplUtil;
import com.starpl.mobile.android.platform.common.ads.AdBannerOnClickListener;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;
import com.starpl.mobile.android.platform.component.BaseListHandler;
import com.starpl.mobile.android.platform.domain.CommunityArticle;

/**
 * 일반 커뮤니티를 위한 리스트 핸들러
 * 
 * @author 박우람
 * @since 2011.02.22
 */
public class CommunityListHandler extends BaseListHandler implements AdListener
{
	private static final String TAG = "PlanListHandler";
	private ArrayList<CommunityArticle> mList;
	private HashMap<Integer, Integer> mBadgeMap;
	private int mNextPage;
	private String mUserId;
	private int mKeywordIdx;
	
	/**
	 * 기본 생성자
	 * 
	 * @param activity 엑티비티
	 * @param userId 사용자 아이디
	 * @param keywordIdx 키워드 인덱스
	 */
	public CommunityListHandler(Activity activity, String userId, int keywordIdx)
	{
		super(activity);
		
		this.mUserId = userId;
		this.mKeywordIdx = keywordIdx;
		this.mList = new ArrayList<CommunityArticle>();
		this.mBadgeMap = new HashMap<Integer, Integer>();
		this.mNextPage = 1;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getArrayList()
	 */
	@Override
	public ArrayList<?> getArrayList()
	{
		// USAGE : 반환할 리스트 객체 정의
		return mList;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getRowView(int, android.view.View)
	 */
	@Override
	public View getRowView(int position, View convertView)
	{
		// 글 데이터 가져오기
		CommunityArticle article = mList.get(position);
		
		// 배너 광고인지 확인
		String adType = article.getAdType();
		
		if(adType != null && adType.equals("ADTC10"))
		{
			// 일반 배너 광고
				convertView = inflate(R.layout.community_ad_banner);
				ImageView ivBanner = (ImageView) convertView.findViewById(R.id.community_ad_banner_iv_image_banner);
				String url = article.getSubject();
				String image = article.getPostImgPath();
				int adIdx = article.getBadgeType();
				
				// 클릭이벤트 추가
				ivBanner.setOnClickListener(new AdBannerOnClickListener(url, adIdx, mKeywordIdx));
				
				ImageDownloader.download(image, ivBanner);
				
				// 광고
				convertView.setId(1);
				return convertView;
		}
		// NBIZ 광고
		else if(adType != null && adType.equals("ADTC51"))
		{
			convertView = inflate(R.layout.nbiz_ad_banner);
			TextView tvAdTitle = (TextView) convertView.findViewById(R.id.nbiz_ad_banner_tv_nbiz_title);
			TextView tvAdDesc = (TextView) convertView.findViewById(R.id.nbiz_ad_banner_tv_nbiz_description);
			ImageView ivBanner = (ImageView) convertView.findViewById(R.id.nbiz_ad_banner_iv_banner);
			
			int adIdx = article.getBadgeType();

			tvAdTitle.setText(article.getSubject());
			tvAdDesc.setText(article.getParentSubject());

			convertView.setVisibility(FrameLayout.VISIBLE);
			ivBanner.setOnClickListener(new AdBannerOnClickListener(article.getStarName(), adIdx, mKeywordIdx));

			ImageDownloader.download(article.getPostImgPath(), ivBanner);

			// 광고
			convertView.setId(1);
			return convertView;
		}
		// CAULY 광고
		else if(adType != null && adType.equals("ADTC52"))
		{
			convertView = mInflater.inflate(R.layout.cauly_row, null);
			RelativeLayout layout = (RelativeLayout)convertView.findViewById(R.id.cauly_row_rl_layout);
			layout.removeAllViews();

			Object tag = article.getTag();
			
			if(tag != null)
			{
				AdView adView = (AdView) tag;
				
				if(adView.getTag() != null)
				{
					layout = (RelativeLayout) adView.getTag();
					layout.removeAllViews();
				}
				
				layout = (RelativeLayout)convertView.findViewById(R.id.cauly_row_rl_layout);
				layout.addView(adView);
				
				adView.setTag(layout);
			}
			
			
			convertView.setId(1);
			return convertView;
		}
		else if(convertView == null || convertView.getId() > 0)
		{
			// USAGE : 인플레이터 활용
			convertView = inflate(R.layout.community_default_row);
		}
		
		LinearLayout llBackground = (LinearLayout) convertView.findViewById(R.id.community_default_row_ll_background);
		ImageView ivProfileImage = (ImageView) convertView.findViewById(R.id.community_default_row_iv_profile);
		TextView tvComment = (TextView) convertView.findViewById(R.id.community_default_row_tv_comment);
		TextView tvNickName = (TextView) convertView.findViewById(R.id.community_default_row_tv_nickname);
		TextView tvWrittenDate = (TextView) convertView.findViewById(R.id.community_default_row_tv_date);
		TextView tvReplyLabel = (TextView) convertView.findViewById(R.id.community_default_row_tv_reply_label);
		TextView tvReplyCount = (TextView) convertView.findViewById(R.id.community_default_row_tv_reply_count);
		ImageView ivThumbnail = (ImageView) convertView.findViewById(R.id.community_default_row_iv_thumbnail);
		
		TextView tvToNickName = (TextView) convertView.findViewById(R.id.community_re_reply_row_tv_to_nickname);
		LinearLayout llOriginalLayout = (LinearLayout) convertView.findViewById(R.id.community_reply_row_ll_origin_article);
		ImageView ivOriginalProfileImage = (ImageView) convertView.findViewById(R.id.community_reply_row_iv_origin_profile);
		TextView tvOriginalComment = (TextView) convertView.findViewById(R.id.community_reply_row_tv_origin_comment);
		ImageView ivBadge = (ImageView) convertView.findViewById(R.id.community_default_row_iv_badge);
		ImageView ivAdFlag = (ImageView) convertView.findViewById(R.id.community_default_row_iv_advertise);
		
		// 사용자 프로필
		String profileUrl = StarplUtil.addSizeTag(article.getProfileImgPath(), "60", "profile");
		ImageDownloader.download(profileUrl, ivProfileImage, true);
		
		// 글
		tvComment.setText(article.getSubject());

		// 닉네임
		tvNickName.setText(article.getStarName());
		
		// 글 작성 시각
		tvWrittenDate.setText(article.getWrittenDate());
		
		// 댓글 숫자
		int replyCount = article.getReplyCount();
		if(replyCount > 0)
		{
			tvReplyLabel.setVisibility(TextView.VISIBLE);
			tvReplyCount.setVisibility(TextView.VISIBLE);
			tvReplyCount.setText("(" + article.getReplyCount() + ")");
		}
		else
		{
			tvReplyLabel.setVisibility(TextView.INVISIBLE);
			tvReplyCount.setVisibility(TextView.INVISIBLE);
		}
		
		// 첨부 이미지
		String thumbnail = article.getPostImgPath();
		if(thumbnail != null && thumbnail.length() > 0)
		{
			thumbnail = StarplUtil.addSizeTag(thumbnail, "66", "thumbnail");
			ImageDownloader.download(thumbnail, ivThumbnail);
			ivThumbnail.setVisibility(ImageView.VISIBLE);
		}
		else
		{
			ivThumbnail.setVisibility(ImageView.GONE);
		}
		
		// 글의 상태에 맞는 추가 정보 표기
		switch(article.getType())
		{
		case CommunityArticle.TYPE_ORIGINAL:
			tvToNickName.setVisibility(TextView.GONE);
			llOriginalLayout.setVisibility(LinearLayout.GONE);
			break;
		case CommunityArticle.TYPE_REPLY:
			tvToNickName.setVisibility(TextView.GONE);
			llOriginalLayout.setVisibility(LinearLayout.VISIBLE);
			thumbnail = StarplUtil.addSizeTag(article.getParentProfileImgPath(), "30", "thumbnail");
			ImageDownloader.download(thumbnail, ivOriginalProfileImage, true);
			tvOriginalComment.setText(article.getParentSubject());
			break;
		case CommunityArticle.TYPE_REPLY_OF_REPLY:
			tvToNickName.setVisibility(TextView.VISIBLE);
			tvToNickName.setText("To. " + article.getBrotherStarName());
			llOriginalLayout.setVisibility(LinearLayout.VISIBLE);
			thumbnail = StarplUtil.addSizeTag(article.getParentProfileImgPath(), "30", "thumbnail");
			ImageDownloader.download(thumbnail, ivOriginalProfileImage, true);
			tvOriginalComment.setText(article.getParentSubject());
			break;
		}
		
		// 배지 정보 표시
		Integer badgeType = mBadgeMap.get(article.getUserIdx());
		if(badgeType != null)
		{
			switch(badgeType)
			{
			case 1:
				ivBadge.setVisibility(ImageView.VISIBLE);
				ivBadge.setImageResource(R.drawable.icon_master);
				break;
			case 2:
				ivBadge.setVisibility(ImageView.VISIBLE);
				ivBadge.setImageResource(R.drawable.icon_senior);
				break;
			case 3:
				ivBadge.setVisibility(ImageView.VISIBLE);
				ivBadge.setImageResource(R.drawable.icon_junior);
				break;
			}
		}
		else
		{
			ivBadge.setVisibility(ImageView.GONE);
		}
		
		// 이슈, 마스터, 리서치에 따른 변화 처리
		// 리서치
		if(adType != null)
		{
			if(adType.equals("ADTC20"))
			{
				llBackground.setBackgroundColor(Color.parseColor("#e6f4fa"));
				ivAdFlag.setImageResource(R.drawable.mark_research);
				ivAdFlag.setVisibility(ImageView.VISIBLE);
			}
			// 이슈
			else if(adType.equals("ADTC30"))
			{
				llBackground.setBackgroundColor(Color.parseColor("#dedede"));
				ivAdFlag.setImageResource(R.drawable.mark_issue);
				ivAdFlag.setVisibility(ImageView.VISIBLE);
			}
			// 마스터
			else if(adType.equals("ADTC40"))
			{
				llBackground.setBackgroundColor(Color.parseColor("#ffffea"));
				ivAdFlag.setImageResource(R.drawable.mark_master);
				ivAdFlag.setVisibility(ImageView.VISIBLE);
			}
		}
		else
		{
			llBackground.setBackgroundColor(Color.parseColor("#ededed"));
			ivAdFlag.setVisibility(ImageView.GONE);
		}
		
		// 태그 입력
		convertView.setTag(position);
		
		// 일반 글
		convertView.setId(0);
		
		return convertView;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClick(android.view.View)
	 */
	@Override
	public void onRowClick(View v)
	{
		// USAGE : 광고
		// 광고 배너일 경우 클릭 무시
		if(v.getId() == 1)
		{
			return;
		}
		// USAGE
		
		UserInfo userInfo = (UserInfo)BaseApplication.getGlobalPersistent("userInfo");
		CommunityArticle article = mList.get((Integer) v.getTag());
		Bundle extras = new Bundle();
		extras.putString("userId", userInfo.getUserId());
		extras.putInt("userIdx", userInfo.getUserIdx());
		extras.putInt("postIdx", article.getPostIdx());
		extras.putInt("keywordIdx", mKeywordIdx);
		extras.putString("nickname", article.getStarName());
		
		getNewActivity()
			.setBundle(extras)
			.setRequestCode(1)
			.setTargetActivity(CommunityCommentActivity.class)
			.show();
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClear()
	 */
	@Override
	public void onRowClear()
	{
		// USAGE : 리프레시등에 의하여 데이터를 삭제할경우 사용되는 로직
		mList.clear();
		mNextPage = 1;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#loadContent()
	 */
	@Override
	public void loadContent()
	{
		HttpHandler httpHandler = new HttpHandler(mParentActivity, null)
		{
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject articleObject = (JSONObject) result;
					JSONArray articleArray = articleObject.getJSONArray("data");
					
					// 글 리스트를 객체화 한다.
					int articleCount = articleArray.length();
					CommunityArticle article;
					
					for(int i = 0 ; i < articleCount ; i++)
					{
						article = new CommunityArticle(articleArray.getJSONObject(i));

						mList.add(article);
					}
					
					// 광고 및 이슈 처리를 한다.
					if(!articleObject.isNull("extData3"))
					{
						JSONObject adObject = articleObject.getJSONObject("extData3");
						String adType = adObject.getString("adType");
						int row = adObject.getInt("row");
						int adIdx = adObject.getInt("adIdx");
						int listRow = articleArray.length();
						
						// row값 보정
						if(row > listRow)
						{
							row = listRow;
						}
						
						int targetRow = mList.size() - listRow + row;
						
						// 배너 광고
						CommunityArticle adArticle;
						if(adType.equals("ADTC10"))
						{
							String url = adObject.getString("url");
							String image = adObject.getString("image");
							
							adArticle = new CommunityArticle();
							adArticle.setSubject(url);
							adArticle.setPostImgPath(image);
							adArticle.setAdType(adType);
							adArticle.setBadgeType(adIdx);
							
							mList.add(targetRow, adArticle);
						}
						// NBIZ광고
						else if(adType.equals("ADTC51"))
						{
							JSONObject adData = (JSONObject) adObject.getJSONObject("adData")
																	.getJSONObject("zetadoc")
																	.getJSONObject("ads")
																	.getJSONArray("ad")
																	.get(0);
							String title = adData.getString("title");
							String description = adData.getString("description");
							String url = adData.getString("landingUrl");
							String image = "http://shared.starpl.com/images2/ad/mobile/ad_back_android_480_78.png";
							
							adArticle = new CommunityArticle();
							adArticle.setSubject(title);
							adArticle.setParentSubject(description);
							adArticle.setStarName(url);
							adArticle.setPostImgPath(image);
							adArticle.setAdType(adType);
							adArticle.setBadgeType(adIdx);
							
							mList.add(targetRow, adArticle);
						}
						// CAULY 광고
						else if(adType.equals("ADTC52"))
						{
							adArticle = new CommunityArticle();
							adArticle.setAdType(adType);
							adArticle.setBadgeType(adIdx);
							
							AdInfo info = new AdInfo();
							info.initData(BaseApplication.getConfigPersistent("caulyCode"), "CPC", "all", "all", "off", "default", "yes", 90, true);
							
							// 광고 뷰 생성
							AdView adView = new AdView(mParentActivity);
							RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
									LayoutParams.WRAP_CONTENT);
							adView.setLayoutParams(params);
							adView.setVisibility(View.VISIBLE);
							adView.setAdListener(CommunityListHandler.this);
							
							adArticle.setTag(adView);
							
							mList.add(targetRow, adArticle);
						}
						// 기타 이슈, 마스터, 리서치
						else if(adType.equals("ADTC20") || adType.equals("ADTC30") || adType.equals("ADTC40"))
						{
							adArticle = new CommunityArticle(adObject);
							
							mList.add(targetRow, adArticle);
						}
					}
					
					// 다음페이지 처리를 한다.
					JSONObject pageObject = articleObject.getJSONObject("extData1");
					mNextPage = pageObject.getInt("nextPageNum");
					
					// 다음 페이지가 있을경우 자동 다음페이지를 읽을수 있도록 설정한다.
					if(mNextPage > 0)
					{
						// USAGE : 페이징처리를 하고 있고 다음페이지가 존재할 경우 다음을 호출해야 한다.
						toggleLockListView();
					}
					else
					{
						// USAGE : 푸터뷰를 삭제합니다.
						removeFooterView();
					}
					
					notifyDataSetChanged();
				}
				catch(JSONException e)
				{
					Log.e(TAG, e.getMessage());
				}
			}
		};
		TelephonyManager telManager = (TelephonyManager) mParentActivity.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = telManager.getDeviceId();
		StarplCommand.getKeywordContent(httpHandler, mUserId, deviceId, mKeywordIdx, mNextPage++);
	}

	@Override
	public View getHeaderView()
	{
		final View convertView = inflate(R.layout.community_header);
		HttpHandler httpHandler = new HttpHandler(mParentActivity)
		{
			@Override
			public void didSucceed(Object result)
			{
				JSONObject object = (JSONObject) result;
				try
				{
					// 일반 헤더 데이터
					JSONObject keywordInfo = object.getJSONObject("data");
					String title = keywordInfo.isNull("keywordName") ? "" : keywordInfo.getString("keywordName");
					String text = keywordInfo.isNull("keywordDesc") ? "" : keywordInfo.getString("keywordDesc");
					String memberCount = keywordInfo.isNull("connectedCount") ? "" : keywordInfo.getString("connectedCount");
					String articleCount = keywordInfo.isNull("postCount") ? "" : keywordInfo.getString("postCount");
					String imgUrl = keywordInfo.isNull("keywordImgPath") ? "" : keywordInfo.getString("keywordImgPath");
					
					ImageView ivKeywordInfo = (ImageView) convertView.findViewById(R.id.community_header_iv_keywordinfo); 
					TextView tvTitle = (TextView) convertView.findViewById(R.id.community_header_tv_title); 
					TextView tvMemberCount = (TextView) convertView.findViewById(R.id.community_header_tv_member_count); 
					TextView tvArticleCount = (TextView) convertView.findViewById(R.id.community_header_tv_article_count); 
					TextView tvKeywordText = (TextView) convertView.findViewById(R.id.community_header_tv_text);
					
					ImageDownloader.download(imgUrl, ivKeywordInfo, true);
					tvTitle.setText(title);
					tvMemberCount.setText(memberCount);
					tvArticleCount.setText(articleCount);
					tvKeywordText.setText(text);
					
					// 추가 배지 데이터
					JSONObject extData = object.getJSONObject("extData1");
					JSONArray badgeData = extData.getJSONArray("topUser");
					
					int badgeCount = badgeData.length();
					for(int i = 0 ; i < badgeCount ; i++)
					{
						JSONObject badge = (JSONObject) badgeData.get(i);
						mBadgeMap.put(badge.getInt("userIdx"), badge.getInt("badgeType"));
					}
				}
				catch(JSONException e)
				{
					Log.e(TAG, e.getMessage());
				}
			}
		};
		
		StarplCommand.getKeywordInfo(httpHandler, mUserId, mKeywordIdx);
		
		return convertView;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getFooterView()
	 */
	@Override
	public View getFooterView()
	{
		// USAGE : 푸터를 반환한다.
		return inflate(R.layout.community_footer);
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onInit()
	 */
	@Override
	public void onInit()
	{
		showHeaderView();
		showFooterView();
		
		// USAGE : 어댑터를 붙인다. 실제로 데이터와 리스트뷰가 연결된다.
		setAdapter();
		
		// USAGE : 리스트의 데이터를 수동으로 호출한다.
		loadContent();
	}

	/* (non-Javadoc)
	 * @see com.cauly.android.ad.AdListener#onFailedToReceiveAd(boolean)
	 */
	@Override
	public void onFailedToReceiveAd(boolean state)
	{
		Log.e("CommunityAdapter", state + "in onFailedToReceiveAd");
	}

	/* (non-Javadoc)
	 * @see com.cauly.android.ad.AdListener#onReceiveAd()
	 */
	@Override
	public void onReceiveAd()
	{
		Log.e("CommunityAdapter", "OK in onReceiveAd");
	}
}
